const { ipcRenderer } = require('electron');
const { exec } = require('child_process');
const path = require('path');

let isMonitoring = false;
let isStartingBrowser = false;
let isBrowserReady = false;

// 获取DOM元素
const logContainer = document.getElementById('logContainer');
const statusElement = document.getElementById('status');
const startBrowserBtn = document.getElementById('startBrowser');
const startMonitoringBtn = document.getElementById('startMonitoring');
const stopMonitoringBtn = document.getElementById('stopMonitoring');

/**
 * 添加日志消息到日志容器
 * @param {string} message - 日志消息
 * @param {string} type - 日志类型
 */
function addLog(message, type = 'info') {
    const logEntry = document.createElement('div');
    logEntry.className = `log-entry ${type}`;
    
    // 添加时间戳
    const now = new Date();
    const timeStr = now.toLocaleTimeString('zh-CN');
    
    // 转换日志类型为中文
    let typeText = '';
    switch(type) {
        case 'info':
            typeText = '信息';
            break;
        case 'success':
            typeText = '成功';
            break;
        case 'warning':
            typeText = '警告';
            break;
        case 'error':
            typeText = '错误';
            break;
        default:
            typeText = type;
    }
    
    logEntry.innerHTML = `<span class="time">[${timeStr}]</span> <span class="type">[${typeText}]</span> ${message}`;
    logContainer.appendChild(logEntry);
    logContainer.scrollTop = logContainer.scrollHeight;
}

/**
 * 更新状态显示
 * @param {boolean} connected - 是否已连接
 */
function updateStatus(connected) {
    if (statusElement) {
        statusElement.className = `status ${connected ? 'connected' : 'disconnected'}`;
        statusElement.textContent = connected ? '已连接' : '未连接';
    }
}

/**
 * 初始化按钮状态
 */
function initializeButtons() {
    startMonitoringBtn.disabled = true;
    stopMonitoringBtn.disabled = true;
    startBrowserBtn.disabled = false;
    
    startBrowserBtn.style.backgroundColor = 'var(--primary-color)';
    startMonitoringBtn.style.backgroundColor = '#bdbdbd';
    stopMonitoringBtn.style.backgroundColor = '#bdbdbd';
    
    updateStatus(false);
}

/**
 * 更新按钮状态
 */
function updateButtonStates() {
    // 启动浏览器按钮状态
    if (startBrowserBtn) {
        if (isStartingBrowser) {
            startBrowserBtn.disabled = true;
            startBrowserBtn.innerHTML = '正在启动浏览器...';
            startBrowserBtn.style.backgroundColor = '#bdbdbd';
            startBrowserBtn.style.cursor = 'not-allowed';
        } else if (isBrowserReady) {
            startBrowserBtn.disabled = true;
            startBrowserBtn.innerHTML = '浏览器已就绪';
            startBrowserBtn.style.backgroundColor = 'var(--success-color)';
            startBrowserBtn.style.cursor = 'not-allowed';
        } else {
            startBrowserBtn.disabled = false;
            startBrowserBtn.innerHTML = '启动浏览器';
            startBrowserBtn.style.backgroundColor = 'var(--primary-color)';
            startBrowserBtn.style.cursor = 'pointer';
        }
    }

    // 监控按钮状态
    if (startMonitoringBtn) {
        if (isBrowserReady && !isMonitoring) {
            startMonitoringBtn.disabled = false;
            startMonitoringBtn.innerHTML = '开始监控';
            startMonitoringBtn.style.backgroundColor = 'var(--success-color)';
            startMonitoringBtn.style.cursor = 'pointer';
        } else if (isMonitoring) {
            startMonitoringBtn.disabled = true;
            startMonitoringBtn.innerHTML = '监控中...';
            startMonitoringBtn.style.backgroundColor = '#bdbdbd';
            startMonitoringBtn.style.cursor = 'not-allowed';
        } else {
            startMonitoringBtn.disabled = true;
            startMonitoringBtn.innerHTML = '开始监控';
            startMonitoringBtn.style.backgroundColor = '#bdbdbd';
            startMonitoringBtn.style.cursor = 'not-allowed';
        }
    }

    // 停止监控按钮状态
    if (stopMonitoringBtn) {
        stopMonitoringBtn.disabled = !isMonitoring;
        stopMonitoringBtn.style.backgroundColor = isMonitoring ? 'var(--danger-color)' : '#bdbdbd';
        stopMonitoringBtn.style.cursor = isMonitoring ? 'pointer' : 'not-allowed';
    }
}

// 监听日志消息
ipcRenderer.on('log-message', (event, message, type = 'info') => {
    addLog(message, type);
});

// 监听浏览器就绪状态
ipcRenderer.on('browser-ready', (event, ready) => {
    console.log('[DEBUG] 收到browser-ready事件:', ready);
    isBrowserReady = ready;
    isStartingBrowser = false;
    console.log('[DEBUG] 更新状态:', { isBrowserReady, isStartingBrowser });
    updateButtonStates();
    updateStatus(ready);
    
    if (ready) {
        addLog('浏览器已就绪，请点击"开始监控"按钮开始自动回复', 'success');
    } else {
        addLog('浏览器连接失败，请重试', 'error');
        isStartingBrowser = false;
        isBrowserReady = false;
        updateButtonStates();
    }
});

// 监听状态更新
ipcRenderer.on('status-update', (event, connected) => {
    console.log('[DEBUG] 收到status-update事件:', connected);
    updateStatus(connected);
    if (!connected) {
        isMonitoring = false;
        updateButtonStates();
    }
});

// 监听窗口最小化事件
ipcRenderer.on('window-minimized', () => {
    addLog('窗口已最小化', 'info');
});

// 监听窗口恢复事件
ipcRenderer.on('window-restored', () => {
    addLog('窗口已恢复', 'info');
});

// 启动浏览器按钮点击事件
startBrowserBtn.addEventListener('click', () => {
    console.log('[DEBUG] 点击启动浏览器按钮');
    if (isStartingBrowser || isBrowserReady) {
        console.log('[DEBUG] 浏览器已在启动中或已就绪，忽略点击');
        return;
    }

    isStartingBrowser = true;
    isBrowserReady = false;
    console.log('[DEBUG] 更新状态:', { isStartingBrowser, isBrowserReady });
    updateButtonStates();
    addLog('正在启动浏览器，请稍候...', 'info');

    ipcRenderer.send('start-browser');
});

// 开始监控按钮点击事件
startMonitoringBtn.addEventListener('click', () => {
    if (!isBrowserReady || isMonitoring) {
        return;
    }

    isMonitoring = true;
    updateButtonStates();
    updateStatus(true);
    ipcRenderer.send('start-monitoring');
    addLog('开始监控消息...', 'info');
});

// 停止监控按钮点击事件
stopMonitoringBtn.addEventListener('click', () => {
    if (!isMonitoring) {
        return;
    }

    isMonitoring = false;
    updateButtonStates();
    updateStatus(false);
    ipcRenderer.send('stop-monitoring');
    addLog('已停止监控消息', 'info');
});

// 初始化
initializeButtons(); 